package com.wswy.wzcx.ui.main.home

import android.content.Context
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTFeedAd
import com.wswy.wzcx.module.ad.AdConfigLoader
import com.wswy.wzcx.module.ad.TTAdManagerHolder
import com.wswy.wzcx.ui.adapter.NewsAdapter3
import java.util.concurrent.atomic.AtomicLong


class FeedAdController(private val context: Context,
                       private val adapter:NewsAdapter3,
                       private val firstAdPosition:Int
                       ) {

    companion object {
        private const val TAG = "FeedAdController"

        private const val MAX_LOAD = 3

    }


    private val adLoadSeq  = AtomicLong()

    @Volatile private var currLoadId = adLoadSeq.get()

    init {
        TTAdManagerHolder.getInstance(context).requestPermissionIfNecessary(context)

    }


    private val adSlot = AdSlot.Builder()
            .setCodeId( AdConfigLoader.csjConfig.feedId) // 903230875 903230649
            .setSupportDeepLink(true)
            .setImageAcceptedSize(640, 320)
            .setAdCount(3)
            .build()
    private val ttAdNative = TTAdManagerHolder.getInstance(context).createAdNative(context)


    fun loadAd(){


        currLoadId = adLoadSeq.incrementAndGet()
        val listener  = AdListener(currLoadId)


        for (i in 0 until MAX_LOAD){
            ttAdNative.loadFeedAd(adSlot,listener)
        }


    }

    inner class AdListener(private val loadId:Long): TTAdNative.FeedAdListener{

        private var count = 0
        private val datas = arrayListOf<TTFeedAd>()

        override fun onFeedAdLoad(ads: MutableList<TTFeedAd>?) {
            count++

            if (loadId == currLoadId){
                //只显示大图
                ads?.filter { supportAd(it) }?.run {
                    datas.addAll(ads)
                }

                ifEndShow()
            }
        }

        override fun onError(code: Int, message: String?) {
            count++
            if (loadId == currLoadId){

                ifEndShow()
            }
        }

        private fun ifEndShow(){
            if (count == MAX_LOAD && datas.isNotEmpty()){
                addToAdapter(datas)
            }
        }
    }

    private fun addToAdapter(ads:List<TTFeedAd>){

        ads.forEachIndexed { index, ttFeedAd ->
            val position = firstAdPosition + 4 * index
            adapter.addTDADs(position, ttFeedAd)
        }

        adapter.notifyDataSetChanged()

    }


    private fun supportAd(ttFeedAd: TTFeedAd):Boolean{
        return when(ttFeedAd.imageMode){
            TTAdConstant.IMAGE_MODE_LARGE_IMG,
            TTAdConstant.IMAGE_MODE_SMALL_IMG,
            TTAdConstant.IMAGE_MODE_GROUP_IMG,
            TTAdConstant.IMAGE_MODE_VIDEO -> true
            else -> false
        }
    }

}